package com.wzy.flyweight;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: wzy
 * @Date: 2021/12/05/13:53
 * @Description: 享元工厂FlyweightFactory负责维护一个享元对象存储池（Flyweight Pool）来存放内部状态的对象。
 * 为了调用方便，该工厂类一般使用单例模式来实现。
 */

public class FlyweightFactory {

    // 用来登记和存储已经创建过的享元对象
    private Map<String, Flyweight> flyweightMap = new HashMap<String, Flyweight>();

    // 采用单例模式
    private static volatile FlyweightFactory flyweightFactory;

    // 私有化享元工厂的构造方法
    private FlyweightFactory() {
    }

    // 获取单例享元工厂的实例
    public static FlyweightFactory getFlyweightFactory() {
        if (flyweightFactory == null) {
            synchronized (FlyweightFactory.class) {
                if (flyweightFactory == null) {
                    flyweightFactory = new FlyweightFactory();
                }
            }
        }
        return flyweightFactory;
    }

    public Flyweight getFlyweight(String intrinsicState) {
        Flyweight flyweight = flyweightMap.get(intrinsicState);
        if (null == flyweight) {
            flyweight = new ConcreteFlyweight(intrinsicState);
            flyweightMap.put(intrinsicState, flyweight);
        }
        return flyweight;
    }

    /**
     * 获取 unsharedFlyweight
     *
     * @param intrinsicStates
     * @return
     */
    public UnsharedConcreteFlyweight getUnsharedFlyweight(List<String> intrinsicStates) {
        UnsharedConcreteFlyweight unsharedFlyweight = new UnsharedConcreteFlyweight();
        for (String intrinsicState : intrinsicStates) {
            unsharedFlyweight.add(intrinsicState, getFlyweight(intrinsicState));
        }
        return unsharedFlyweight;
    }


    public Map<String, Flyweight> getFlyweightMap() {
        return flyweightMap;
    }

}
